"""EDA处理器高级功能使用示例

演示EDA处理器的高级功能，包括：
- 高级处理管道配置
- 自定义预处理流程
- 详细质量评估
- 多算法比较
- 参数优化

适合有经验的用户进行深度分析。
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
import logging
from typing import Dict, Any, List, Optional, Tuple
import json

# 导入EDA处理器模块
from ..core.pipeline import process_eda_pipeline
from ..core.registry import get_algorithm, list_available_algorithms
from ..algorithms.preprocessors import preprocess_improved
from ..algorithms.peak_detectors import detect_peaks_improved
from ..algorithms.metrics_calculators import calculate_metrics_advanced
from ..algorithms.quality_assessors import assess_quality_comprehensive
from ..utils.data_io import load_eda_data, save_eda_results
from ..utils.visualization import plot_eda_signal, plot_peak_detection, plot_frequency_analysis

# 设置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def advanced_processing_pipeline_example(data_file: str = None,
                                       output_dir: str = None) -> Dict[str, Any]:
    """高级处理管道示例
    
    演示如何配置和使用高级处理管道，包括：
    1. 多级预处理
    2. 自适应峰值检测
    3. 全面指标计算
    4. 详细质量评估
    
    Args:
        data_file: EDA数据文件路径
        output_dir: 输出目录路径
        
    Returns:
        处理结果字典
    """
    print("=" * 60)
    print("EDA高级处理管道示例")
    print("=" * 60)
    
    try:
        # 1. 准备数据
        if data_file and Path(data_file).exists():
            print(f"加载数据文件: {data_file}")
            eda_data = load_eda_data(data_file)
        else:
            print("生成复杂模拟EDA数据...")
            eda_data = generate_complex_eda_data()
        
        print(f"数据概况:")
        print(f"  信号长度: {len(eda_data['signal'])} 个采样点")
        print(f"  采样率: {eda_data.get('sampling_rate', 4.0)} Hz")
        print(f"  信号时长: {len(eda_data['signal']) / eda_data.get('sampling_rate', 4.0):.2f} 秒")
        
        # 2. 高级处理配置
        advanced_config = {
            'preprocessing': {
                'algorithm': 'improved',
                'params': {
                    'outlier_method': 'iqr',
                    'outlier_threshold': 2.5,
                    'smooth_method': 'savgol',
                    'smooth_window': 7,
                    'detrend_method': 'polynomial',
                    'detrend_order': 2,
                    'lowpass_freq': 1.0,
                    'filter_order': 4,
                    'adaptive_filtering': True,
                    'quality_threshold': 0.7
                }
            },
            'peak_detection': {
                'algorithm': 'improved',
                'params': {
                    'adaptive_threshold': True,
                    'min_amplitude': 0.005,
                    'min_duration': 0.5,
                    'max_duration': 15.0,
                    'prominence_factor': 0.3,
                    'width_factor': 0.5,
                    'multi_scale': True,
                    'false_positive_filter': True,
                    'quality_assessment': True
                }
            },
            'metrics_calculation': {
                'algorithm': 'advanced',
                'params': {
                    'frequency_bands': {
                        'very_low': (0.0, 0.05),
                        'low': (0.05, 0.15),
                        'mid': (0.15, 0.25),
                        'high': (0.25, 0.4)
                    },
                    'complexity_measures': True,
                    'morphological_features': True,
                    'variability_measures': True
                }
            },
            'quality_assessment': {
                'algorithm': 'comprehensive',
                'params': {
                    'artifact_detection': True,
                    'signal_consistency': True,
                    'physiological_validity': True,
                    'frequency_domain_quality': True,
                    'context_analysis': True,
                    'temporal_quality': True
                }
            }
        }
        
        print("\n高级处理配置:")
        for step, step_config in advanced_config.items():
            print(f"  {step}:")
            print(f"    算法: {step_config['algorithm']}")
            print(f"    参数数量: {len(step_config['params'])}")
        
        # 3. 执行高级处理
        print("\n开始高级处理...")
        results = process_eda_pipeline(eda_data, advanced_config)
        
        if not results['success']:
            print(f"处理失败: {results.get('error', '未知错误')}")
            return results
        
        # 4. 详细结果分析
        print("\n高级处理完成！")
        analyze_advanced_results(results)
        
        # 5. 保存详细结果
        if output_dir:
            output_path = Path(output_dir)
            output_path.mkdir(parents=True, exist_ok=True)
            
            # 保存完整结果
            results_file = output_path / "advanced_processing_results.json"
            save_eda_results(results, str(results_file))
            
            # 生成详细报告
            generate_advanced_report(eda_data, results, output_path)
            
            print(f"\n详细结果已保存到: {output_path}")
        
        return results
        
    except Exception as e:
        logger.error(f"高级处理示例执行失败: {str(e)}")
        return {'success': False, 'error': str(e)}

def custom_preprocessing_example(eda_data: Dict[str, Any] = None) -> Dict[str, Any]:
    """自定义预处理示例
    
    演示如何实现和使用自定义预处理流程
    
    Args:
        eda_data: EDA数据字典
        
    Returns:
        预处理结果
    """
    print("=" * 60)
    print("自定义预处理示例")
    print("=" * 60)
    
    try:
        # 准备数据
        if eda_data is None:
            print("生成带噪声的模拟EDA数据...")
            eda_data = generate_noisy_eda_data()
        
        signal = eda_data['signal']
        sampling_rate = eda_data.get('sampling_rate', 4.0)
        
        print(f"原始信号统计:")
        print(f"  长度: {len(signal)} 个采样点")
        print(f"  均值: {np.mean(signal):.4f}")
        print(f"  标准差: {np.std(signal):.4f}")
        print(f"  范围: [{np.min(signal):.4f}, {np.max(signal):.4f}]")
        
        # 1. 基本预处理
        print("\n1. 基本预处理...")
        basic_params = {
            'outlier_threshold': 3.0,
            'smooth_window': 5,
            'lowpass_freq': 1.0
        }
        
        basic_result = preprocess_improved(signal, sampling_rate, **basic_params)
        basic_signal = basic_result['processed_signal']
        
        print(f"  基本预处理后:")
        print(f"    均值: {np.mean(basic_signal):.4f}")
        print(f"    标准差: {np.std(basic_signal):.4f}")
        print(f"    质量评分: {basic_result.get('quality_score', 0):.3f}")
        
        # 2. 高级预处理
        print("\n2. 高级预处理...")
        advanced_params = {
            'outlier_method': 'iqr',
            'outlier_threshold': 2.5,
            'smooth_method': 'savgol',
            'smooth_window': 7,
            'detrend_method': 'polynomial',
            'detrend_order': 2,
            'lowpass_freq': 1.0,
            'filter_order': 4,
            'adaptive_filtering': True
        }
        
        advanced_result = preprocess_improved(signal, sampling_rate, **advanced_params)
        advanced_signal = advanced_result['processed_signal']
        
        print(f"  高级预处理后:")
        print(f"    均值: {np.mean(advanced_signal):.4f}")
        print(f"    标准差: {np.std(advanced_signal):.4f}")
        print(f"    质量评分: {advanced_result.get('quality_score', 0):.3f}")
        
        # 3. 自定义预处理流程
        print("\n3. 自定义预处理流程...")
        custom_result = custom_preprocessing_pipeline(signal, sampling_rate)
        custom_signal = custom_result['processed_signal']
        
        print(f"  自定义预处理后:")
        print(f"    均值: {np.mean(custom_signal):.4f}")
        print(f"    标准差: {np.std(custom_signal):.4f}")
        print(f"    质量评分: {custom_result.get('quality_score', 0):.3f}")
        
        # 4. 比较结果
        print("\n预处理方法比较:")
        methods = [
            ('原始信号', signal),
            ('基本预处理', basic_signal),
            ('高级预处理', advanced_signal),
            ('自定义预处理', custom_signal)
        ]
        
        for name, processed_signal in methods:
            snr = calculate_signal_to_noise_ratio(processed_signal)
            smoothness = calculate_signal_smoothness(processed_signal)
            print(f"  {name}:")
            print(f"    信噪比: {snr:.2f} dB")
            print(f"    平滑度: {smoothness:.4f}")
        
        return {
            'success': True,
            'original_signal': signal,
            'basic_processed': basic_signal,
            'advanced_processed': advanced_signal,
            'custom_processed': custom_signal,
            'basic_result': basic_result,
            'advanced_result': advanced_result,
            'custom_result': custom_result
        }
        
    except Exception as e:
        logger.error(f"自定义预处理示例执行失败: {str(e)}")
        return {'success': False, 'error': str(e)}

def quality_assessment_example(eda_data: Dict[str, Any] = None) -> Dict[str, Any]:
    """质量评估示例
    
    演示如何进行全面的EDA信号质量评估
    
    Args:
        eda_data: EDA数据字典
        
    Returns:
        质量评估结果
    """
    print("=" * 60)
    print("EDA信号质量评估示例")
    print("=" * 60)
    
    try:
        # 准备不同质量的数据
        if eda_data is None:
            print("生成不同质量的模拟EDA数据...")
            test_datasets = generate_quality_test_datasets()
        else:
            test_datasets = [('用户数据', eda_data)]
        
        assessment_results = []
        
        for dataset_name, data in test_datasets:
            print(f"\n评估数据集: {dataset_name}")
            print("-" * 40)
            
            signal = data['signal']
            sampling_rate = data.get('sampling_rate', 4.0)
            
            # 执行全面质量评估
            quality_result = assess_quality_comprehensive(
                signal, 
                sampling_rate,
                artifact_detection=True,
                signal_consistency=True,
                physiological_validity=True,
                frequency_domain_quality=True,
                context_analysis=True,
                temporal_quality=True
            )
            
            # 显示评估结果
            print_quality_assessment(quality_result)
            
            assessment_results.append({
                'dataset_name': dataset_name,
                'quality_result': quality_result,
                'signal_stats': {
                    'length': len(signal),
                    'mean': np.mean(signal),
                    'std': np.std(signal),
                    'range': [np.min(signal), np.max(signal)]
                }
            })
        
        # 质量比较
        if len(assessment_results) > 1:
            print("\n质量评估比较:")
            print("-" * 40)
            compare_quality_assessments(assessment_results)
        
        return {
            'success': True,
            'assessment_results': assessment_results
        }
        
    except Exception as e:
        logger.error(f"质量评估示例执行失败: {str(e)}")
        return {'success': False, 'error': str(e)}

def algorithm_comparison_example(eda_data: Dict[str, Any] = None) -> Dict[str, Any]:
    """算法比较示例
    
    比较不同算法的性能和结果
    
    Args:
        eda_data: EDA数据字典
        
    Returns:
        比较结果
    """
    print("=" * 60)
    print("EDA处理算法比较示例")
    print("=" * 60)
    
    try:
        # 准备数据
        if eda_data is None:
            print("生成标准测试EDA数据...")
            eda_data = generate_standard_test_data()
        
        # 定义要比较的算法配置
        algorithm_configs = {
            '基本算法': {
                'preprocessing': {'algorithm': 'basic', 'params': {}},
                'peak_detection': {'algorithm': 'basic', 'params': {}},
                'metrics_calculation': {'algorithm': 'basic', 'params': {}}
            },
            '改进算法': {
                'preprocessing': {'algorithm': 'improved', 'params': {'adaptive_filtering': True}},
                'peak_detection': {'algorithm': 'improved', 'params': {'adaptive_threshold': True}},
                'metrics_calculation': {'algorithm': 'advanced', 'params': {}}
            },
            'NeuroKit2算法': {
                'preprocessing': {'algorithm': 'neurokit2', 'params': {}},
                'peak_detection': {'algorithm': 'neurokit2', 'params': {}},
                'metrics_calculation': {'algorithm': 'all', 'params': {}}
            }
        }
        
        comparison_results = {}
        
        for algo_name, config in algorithm_configs.items():
            print(f"\n测试算法: {algo_name}")
            print("-" * 30)
            
            # 添加质量评估配置
            full_config = config.copy()
            full_config['quality_assessment'] = {
                'algorithm': 'basic',
                'params': {}
            }
            
            # 执行处理
            import time
            start_time = time.time()
            
            result = process_eda_pipeline(eda_data, full_config)
            
            processing_time = time.time() - start_time
            
            if result['success']:
                # 收集性能指标
                metrics = result.get('metrics', {})
                peaks = result.get('peaks', [])
                quality = result.get('quality_assessment', {})
                
                performance_metrics = {
                    'processing_time': processing_time,
                    'peak_count': len(peaks),
                    'quality_score': quality.get('overall_score', 0),
                    'mean_eda': metrics.get('mean_eda', 0),
                    'scr_rate': metrics.get('scr_rate', 0),
                    'signal_quality': metrics.get('signal_quality', 0)
                }
                
                comparison_results[algo_name] = {
                    'success': True,
                    'performance': performance_metrics,
                    'full_result': result
                }
                
                print(f"  处理时间: {processing_time:.3f}s")
                print(f"  检测峰值: {len(peaks)} 个")
                print(f"  质量评分: {quality.get('overall_score', 0):.3f}")
                
            else:
                comparison_results[algo_name] = {
                    'success': False,
                    'error': result.get('error', '未知错误')
                }
                print(f"  处理失败: {result.get('error', '未知错误')}")
        
        # 生成比较报告
        print("\n算法性能比较:")
        print("=" * 60)
        generate_algorithm_comparison_report(comparison_results)
        
        return {
            'success': True,
            'comparison_results': comparison_results,
            'test_data': eda_data
        }
        
    except Exception as e:
        logger.error(f"算法比较示例执行失败: {str(e)}")
        return {'success': False, 'error': str(e)}

# 辅助函数

def generate_complex_eda_data(duration: float = 600.0, 
                            sampling_rate: float = 4.0) -> Dict[str, Any]:
    """生成复杂的模拟EDA数据"""
    t = np.arange(0, duration, 1/sampling_rate)
    n_samples = len(t)
    
    # 复杂基线（多个频率成分）
    baseline = (2.0 + 
                0.5 * np.sin(2 * np.pi * t / 120) +  # 慢变化
                0.3 * np.sin(2 * np.pi * t / 60) +   # 中等变化
                0.1 * np.sin(2 * np.pi * t / 20))    # 快变化
    
    # 添加趋势
    trend = 0.2 * t / duration
    
    # 多种噪声
    white_noise = np.random.normal(0, 0.02, n_samples)
    colored_noise = np.cumsum(np.random.normal(0, 0.005, n_samples))
    
    # 生成多种类型的SCR峰值
    signal = baseline + trend + white_noise + colored_noise * 0.1
    
    # 大幅度SCR峰值
    large_peaks = np.random.uniform(30, duration-30, 5)
    for peak_time in large_peaks:
        amplitude = np.random.uniform(0.2, 0.5)
        add_scr_peak(signal, t, peak_time, amplitude, 2.0, 6.0)
    
    # 中等幅度SCR峰值
    medium_peaks = np.random.uniform(20, duration-20, 8)
    for peak_time in medium_peaks:
        amplitude = np.random.uniform(0.05, 0.2)
        add_scr_peak(signal, t, peak_time, amplitude, 1.5, 4.0)
    
    # 小幅度SCR峰值
    small_peaks = np.random.uniform(10, duration-10, 12)
    for peak_time in small_peaks:
        amplitude = np.random.uniform(0.01, 0.05)
        add_scr_peak(signal, t, peak_time, amplitude, 1.0, 3.0)
    
    # 添加一些伪迹
    artifact_times = np.random.uniform(60, duration-60, 3)
    for artifact_time in artifact_times:
        add_motion_artifact(signal, t, artifact_time)
    
    return {
        'signal': signal,
        'timestamps': t,
        'sampling_rate': sampling_rate,
        'metadata': {
            'duration': duration,
            'complexity': 'high',
            'num_large_peaks': len(large_peaks),
            'num_medium_peaks': len(medium_peaks),
            'num_small_peaks': len(small_peaks),
            'num_artifacts': len(artifact_times),
            'description': '复杂模拟EDA数据，包含多种峰值类型和伪迹'
        }
    }

def generate_noisy_eda_data(duration: float = 300.0,
                          sampling_rate: float = 4.0,
                          noise_level: float = 0.1) -> Dict[str, Any]:
    """生成带噪声的EDA数据"""
    t = np.arange(0, duration, 1/sampling_rate)
    
    # 基本EDA信号
    baseline = 1.8 + 0.4 * np.sin(2 * np.pi * t / 80)
    
    # 添加SCR峰值
    signal = baseline.copy()
    peak_times = np.random.uniform(20, duration-20, 6)
    for peak_time in peak_times:
        amplitude = np.random.uniform(0.1, 0.3)
        add_scr_peak(signal, t, peak_time, amplitude, 1.5, 4.0)
    
    # 添加各种噪声
    white_noise = np.random.normal(0, noise_level * 0.3, len(signal))
    pink_noise = generate_pink_noise(len(signal)) * noise_level * 0.2
    motion_artifacts = generate_motion_artifacts(t, noise_level * 0.5)
    
    signal += white_noise + pink_noise + motion_artifacts
    
    return {
        'signal': signal,
        'timestamps': t,
        'sampling_rate': sampling_rate,
        'metadata': {
            'noise_level': noise_level,
            'description': f'带噪声的EDA数据，噪声水平: {noise_level}'
        }
    }

def generate_quality_test_datasets() -> List[Tuple[str, Dict[str, Any]]]:
    """生成不同质量的测试数据集"""
    datasets = []
    
    # 高质量数据
    high_quality = generate_complex_eda_data(duration=300, sampling_rate=4.0)
    datasets.append(('高质量数据', high_quality))
    
    # 中等质量数据（有噪声）
    medium_quality = generate_noisy_eda_data(duration=300, sampling_rate=4.0, noise_level=0.05)
    datasets.append(('中等质量数据', medium_quality))
    
    # 低质量数据（高噪声）
    low_quality = generate_noisy_eda_data(duration=300, sampling_rate=4.0, noise_level=0.15)
    datasets.append(('低质量数据', low_quality))
    
    # 极低质量数据（大量伪迹）
    very_low_quality = generate_artifact_heavy_data()
    datasets.append(('极低质量数据', very_low_quality))
    
    return datasets

def generate_standard_test_data() -> Dict[str, Any]:
    """生成标准测试数据"""
    return generate_complex_eda_data(duration=240, sampling_rate=4.0)

def add_scr_peak(signal: np.ndarray, t: np.ndarray, peak_time: float, 
                amplitude: float, rise_time: float, recovery_time: float):
    """向信号中添加SCR峰值"""
    peak_indices = np.where((t >= peak_time) & (t <= peak_time + rise_time + recovery_time))[0]
    
    for i in peak_indices:
        time_from_onset = t[i] - peak_time
        
        if time_from_onset <= rise_time:
            # 上升阶段
            progress = time_from_onset / rise_time
            scr_value = amplitude * (1 - np.exp(-3 * progress))
        else:
            # 恢复阶段
            progress = (time_from_onset - rise_time) / recovery_time
            scr_value = amplitude * np.exp(-2 * progress)
        
        signal[i] += scr_value

def add_motion_artifact(signal: np.ndarray, t: np.ndarray, artifact_time: float):
    """添加运动伪迹"""
    artifact_duration = np.random.uniform(2.0, 5.0)
    artifact_indices = np.where((t >= artifact_time) & (t <= artifact_time + artifact_duration))[0]
    
    # 创建尖峰伪迹
    artifact_amplitude = np.random.uniform(0.3, 0.8)
    for i in artifact_indices:
        time_in_artifact = t[i] - artifact_time
        progress = time_in_artifact / artifact_duration
        
        # 快速上升和下降
        if progress < 0.1:
            artifact_value = artifact_amplitude * (progress / 0.1)
        elif progress > 0.9:
            artifact_value = artifact_amplitude * ((1 - progress) / 0.1)
        else:
            artifact_value = artifact_amplitude * (1 + 0.3 * np.sin(20 * np.pi * progress))
        
        signal[i] += artifact_value

def generate_pink_noise(n_samples: int) -> np.ndarray:
    """生成粉红噪声"""
    # 简化的粉红噪声生成
    white = np.random.randn(n_samples)
    
    # 应用1/f滤波器
    freqs = np.fft.fftfreq(n_samples)
    freqs[0] = 1e-10  # 避免除零
    
    fft_white = np.fft.fft(white)
    fft_pink = fft_white / np.sqrt(np.abs(freqs))
    
    pink = np.real(np.fft.ifft(fft_pink))
    return pink / np.std(pink)

def generate_motion_artifacts(t: np.ndarray, amplitude: float) -> np.ndarray:
    """生成运动伪迹"""
    artifacts = np.zeros_like(t)
    
    # 随机添加几个运动伪迹
    num_artifacts = np.random.randint(2, 5)
    artifact_times = np.random.uniform(10, len(t)/4 - 10, num_artifacts)
    
    for artifact_time in artifact_times:
        add_motion_artifact(artifacts, t, artifact_time)
    
    return artifacts * amplitude

def generate_artifact_heavy_data() -> Dict[str, Any]:
    """生成包含大量伪迹的数据"""
    duration = 300.0
    sampling_rate = 4.0
    t = np.arange(0, duration, 1/sampling_rate)
    
    # 基本信号
    baseline = 1.5 + 0.3 * np.sin(2 * np.pi * t / 60)
    signal = baseline.copy()
    
    # 添加少量正常SCR峰值
    peak_times = np.random.uniform(30, duration-30, 3)
    for peak_time in peak_times:
        amplitude = np.random.uniform(0.05, 0.15)
        add_scr_peak(signal, t, peak_time, amplitude, 1.5, 4.0)
    
    # 添加大量伪迹
    artifact_times = np.random.uniform(20, duration-20, 8)
    for artifact_time in artifact_times:
        add_motion_artifact(signal, t, artifact_time)
    
    # 添加高噪声
    noise = np.random.normal(0, 0.1, len(signal))
    signal += noise
    
    return {
        'signal': signal,
        'timestamps': t,
        'sampling_rate': sampling_rate,
        'metadata': {
            'quality': 'very_low',
            'num_artifacts': len(artifact_times),
            'description': '包含大量伪迹的低质量EDA数据'
        }
    }

def custom_preprocessing_pipeline(signal: np.ndarray, 
                                sampling_rate: float) -> Dict[str, Any]:
    """自定义预处理管道"""
    from scipy import signal as scipy_signal
    from scipy.stats import zscore
    
    processed_signal = signal.copy()
    processing_steps = []
    
    # 1. 异常值检测和处理（使用修正的Z分数）
    mad = np.median(np.abs(processed_signal - np.median(processed_signal)))
    modified_z_scores = 0.6745 * (processed_signal - np.median(processed_signal)) / mad
    outlier_mask = np.abs(modified_z_scores) > 3.5
    
    if np.any(outlier_mask):
        # 使用线性插值替换异常值
        outlier_indices = np.where(outlier_mask)[0]
        for idx in outlier_indices:
            # 找到最近的非异常值
            left_idx = idx - 1
            right_idx = idx + 1
            
            while left_idx >= 0 and outlier_mask[left_idx]:
                left_idx -= 1
            while right_idx < len(processed_signal) and outlier_mask[right_idx]:
                right_idx += 1
            
            if left_idx >= 0 and right_idx < len(processed_signal):
                processed_signal[idx] = np.interp(idx, [left_idx, right_idx], 
                                                [processed_signal[left_idx], processed_signal[right_idx]])
        
        processing_steps.append(f"异常值处理: 替换了 {np.sum(outlier_mask)} 个异常值")
    
    # 2. 自适应去趋势
    window_size = int(60 * sampling_rate)  # 60秒窗口
    if len(processed_signal) > window_size:
        # 使用移动中位数去趋势
        trend = scipy_signal.medfilt(processed_signal, kernel_size=window_size)
        processed_signal = processed_signal - trend + np.median(trend)
        processing_steps.append("自适应去趋势: 移动中位数方法")
    
    # 3. 多级平滑
    # 第一级：轻度平滑
    processed_signal = scipy_signal.savgol_filter(processed_signal, 
                                                window_length=5, 
                                                polyorder=2)
    
    # 第二级：根据信号变异性调整平滑强度
    signal_variability = np.std(np.diff(processed_signal))
    if signal_variability > 0.05:  # 高变异性
        processed_signal = scipy_signal.savgol_filter(processed_signal, 
                                                    window_length=7, 
                                                    polyorder=2)
        processing_steps.append("多级平滑: 高变异性，使用强平滑")
    else:
        processing_steps.append("多级平滑: 低变异性，使用轻度平滑")
    
    # 4. 自适应低通滤波
    # 根据信号特征调整截止频率
    nyquist = sampling_rate / 2
    base_cutoff = 1.0
    
    # 分析信号的频谱特征
    freqs, psd = scipy_signal.welch(processed_signal, sampling_rate, nperseg=min(256, len(processed_signal)//4))
    
    # 找到主要能量集中的频率范围
    cumulative_power = np.cumsum(psd) / np.sum(psd)
    cutoff_99 = freqs[np.where(cumulative_power >= 0.99)[0][0]]
    
    adaptive_cutoff = min(base_cutoff, max(0.5, cutoff_99))
    
    # 设计和应用滤波器
    sos = scipy_signal.butter(4, adaptive_cutoff, btype='low', fs=sampling_rate, output='sos')
    processed_signal = scipy_signal.sosfilt(sos, processed_signal)
    
    processing_steps.append(f"自适应低通滤波: 截止频率 {adaptive_cutoff:.2f} Hz")
    
    # 5. 信号质量评估
    # 计算信噪比
    signal_power = np.var(processed_signal)
    noise_estimate = np.var(np.diff(processed_signal)) / 2  # 基于差分的噪声估计
    snr = 10 * np.log10(signal_power / noise_estimate) if noise_estimate > 0 else float('inf')
    
    # 计算平滑度
    smoothness = 1 / (1 + np.std(np.diff(processed_signal, n=2)))
    
    # 综合质量评分
    quality_score = min(1.0, (snr / 20 + smoothness) / 2)
    
    return {
        'processed_signal': processed_signal,
        'quality_score': quality_score,
        'processing_steps': processing_steps,
        'metrics': {
            'snr': snr,
            'smoothness': smoothness,
            'outliers_removed': np.sum(outlier_mask),
            'adaptive_cutoff': adaptive_cutoff
        }
    }

def calculate_signal_to_noise_ratio(signal: np.ndarray) -> float:
    """计算信噪比"""
    signal_power = np.var(signal)
    noise_power = np.var(np.diff(signal)) / 2
    
    if noise_power > 0:
        return 10 * np.log10(signal_power / noise_power)
    else:
        return float('inf')

def calculate_signal_smoothness(signal: np.ndarray) -> float:
    """计算信号平滑度"""
    second_diff = np.diff(signal, n=2)
    return 1 / (1 + np.std(second_diff))

def analyze_advanced_results(results: Dict[str, Any]):
    """分析高级处理结果"""
    print("\n高级处理结果分析:")
    print("=" * 50)
    
    # 预处理分析
    if 'preprocessing_info' in results:
        preprocessing_info = results['preprocessing_info']
        print(f"\n预处理信息:")
        print(f"  质量评分: {preprocessing_info.get('quality_score', 0):.3f}")
        print(f"  处理步骤: {len(preprocessing_info.get('processing_steps', []))}")
        
        steps = preprocessing_info.get('processing_steps', [])
        for step in steps[:3]:  # 显示前3个步骤
            print(f"    - {step}")
    
    # 峰值检测分析
    if 'peaks' in results:
        peaks = results['peaks']
        print(f"\n峰值检测分析:")
        print(f"  检测到峰值: {len(peaks)} 个")
        
        if peaks:
            amplitudes = [p.get('amplitude', 0) for p in peaks]
            durations = [p.get('duration', 0) for p in peaks]
            qualities = [p.get('quality_score', 0) for p in peaks if 'quality_score' in p]
            
            print(f"  幅度统计:")
            print(f"    平均: {np.mean(amplitudes):.4f}")
            print(f"    范围: [{np.min(amplitudes):.4f}, {np.max(amplitudes):.4f}]")
            
            print(f"  持续时间统计:")
            print(f"    平均: {np.mean(durations):.2f}s")
            print(f"    范围: [{np.min(durations):.2f}s, {np.max(durations):.2f}s]")
            
            if qualities:
                print(f"  峰值质量:")
                print(f"    平均质量: {np.mean(qualities):.3f}")
                high_quality_peaks = sum(1 for q in qualities if q > 0.7)
                print(f"    高质量峰值: {high_quality_peaks}/{len(qualities)}")
    
    # 指标分析
    if 'metrics' in results:
        metrics = results['metrics']
        print(f"\n指标分析:")
        print(f"  计算指标数: {len(metrics)}")
        
        # 按类别显示关键指标
        key_metrics = {
            'mean_eda': '平均EDA',
            'std_eda': 'EDA标准差',
            'scr_count': 'SCR数量',
            'scr_rate': 'SCR频率',
            'mean_scr_amplitude': '平均SCR幅度',
            'eda_range': 'EDA范围'
        }
        
        for metric_key, metric_name in key_metrics.items():
            if metric_key in metrics:
                print(f"    {metric_name}: {metrics[metric_key]:.4f}")
    
    # 质量评估分析
    if 'quality_assessment' in results:
        quality = results['quality_assessment']
        print(f"\n质量评估分析:")
        print(f"  总体质量: {quality.get('overall_score', 0):.3f}")
        
        quality_aspects = {
            'completeness_score': '完整性',
            'noise_score': '噪声水平',
            'stability_score': '稳定性',
            'artifact_score': '伪迹检测',
            'consistency_score': '一致性',
            'physiological_score': '生理有效性'
        }
        
        for aspect_key, aspect_name in quality_aspects.items():
            if aspect_key in quality:
                print(f"    {aspect_name}: {quality[aspect_key]:.3f}")
        
        # 显示质量问题
        issues = quality.get('issues', [])
        if issues:
            print(f"  发现问题: {len(issues)} 个")
            for issue in issues[:3]:  # 显示前3个问题
                print(f"    - {issue}")
        
        # 显示建议
        recommendations = quality.get('recommendations', [])
        if recommendations:
            print(f"  处理建议: {len(recommendations)} 条")
            for rec in recommendations[:2]:  # 显示前2条建议
                print(f"    - {rec}")

def print_quality_assessment(quality_result: Dict[str, Any]):
    """打印质量评估结果"""
    overall_score = quality_result.get('overall_score', 0)
    print(f"总体质量评分: {overall_score:.3f}/1.0")
    
    # 各维度评分
    dimensions = {
        'completeness_score': '数据完整性',
        'noise_score': '噪声水平',
        'stability_score': '信号稳定性',
        'artifact_score': '伪迹检测',
        'consistency_score': '信号一致性',
        'physiological_score': '生理有效性',
        'frequency_score': '频域质量',
        'temporal_score': '时域质量'
    }
    
    print("各维度评分:")
    for key, name in dimensions.items():
        if key in quality_result:
            score = quality_result[key]
            status = "优秀" if score > 0.8 else "良好" if score > 0.6 else "一般" if score > 0.4 else "较差"
            print(f"  {name}: {score:.3f} ({status})")
    
    # 问题和建议
    issues = quality_result.get('issues', [])
    if issues:
        print(f"发现问题 ({len(issues)} 个):")
        for issue in issues:
            print(f"  - {issue}")
    
    recommendations = quality_result.get('recommendations', [])
    if recommendations:
        print(f"处理建议 ({len(recommendations)} 条):")
        for rec in recommendations:
            print(f"  - {rec}")

def compare_quality_assessments(assessment_results: List[Dict[str, Any]]):
    """比较质量评估结果"""
    print("数据集质量排名:")
    
    # 按总体质量评分排序
    sorted_results = sorted(assessment_results, 
                          key=lambda x: x['quality_result'].get('overall_score', 0), 
                          reverse=True)
    
    for i, result in enumerate(sorted_results, 1):
        dataset_name = result['dataset_name']
        overall_score = result['quality_result'].get('overall_score', 0)
        signal_stats = result['signal_stats']
        
        print(f"{i}. {dataset_name}")
        print(f"   质量评分: {overall_score:.3f}")
        print(f"   信号长度: {signal_stats['length']} 个采样点")
        print(f"   信号范围: [{signal_stats['range'][0]:.3f}, {signal_stats['range'][1]:.3f}]")

def generate_algorithm_comparison_report(comparison_results: Dict[str, Any]):
    """生成算法比较报告"""
    successful_results = {name: result for name, result in comparison_results.items() 
                         if result['success']}
    
    if not successful_results:
        print("没有成功的算法结果可供比较")
        return
    
    print("算法性能对比表:")
    print("-" * 80)
    print(f"{'算法名称':<15} {'处理时间':<10} {'峰值数量':<10} {'质量评分':<10} {'SCR频率':<10}")
    print("-" * 80)
    
    for algo_name, result in successful_results.items():
        perf = result['performance']
        print(f"{algo_name:<15} "
              f"{perf['processing_time']:<10.3f} "
              f"{perf['peak_count']:<10} "
              f"{perf['quality_score']:<10.3f} "
              f"{perf.get('scr_rate', 0):<10.3f}")
    
    # 找出最佳算法
    print("\n性能总结:")
    
    # 最快算法
    fastest = min(successful_results.items(), 
                 key=lambda x: x[1]['performance']['processing_time'])
    print(f"最快算法: {fastest[0]} ({fastest[1]['performance']['processing_time']:.3f}s)")
    
    # 最高质量算法
    highest_quality = max(successful_results.items(), 
                         key=lambda x: x[1]['performance']['quality_score'])
    print(f"最高质量: {highest_quality[0]} ({highest_quality[1]['performance']['quality_score']:.3f})")
    
    # 检测峰值最多的算法
    most_peaks = max(successful_results.items(), 
                    key=lambda x: x[1]['performance']['peak_count'])
    print(f"检测峰值最多: {most_peaks[0]} ({most_peaks[1]['performance']['peak_count']} 个)")

def generate_advanced_report(eda_data: Dict[str, Any], 
                           results: Dict[str, Any], 
                           output_path: Path):
    """生成高级分析报告"""
    try:
        # 创建详细的可视化
        create_advanced_visualizations(eda_data, results, output_path)
        
        # 生成详细的文本报告
        report_content = create_detailed_text_report(eda_data, results)
        
        report_file = output_path / "advanced_analysis_report.txt"
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write(report_content)
        
        print(f"详细报告已保存: {report_file}")
        
    except Exception as e:
        logger.warning(f"生成高级报告失败: {str(e)}")

def create_advanced_visualizations(eda_data: Dict[str, Any], 
                                 results: Dict[str, Any], 
                                 output_path: Path):
    """创建高级可视化图表"""
    try:
        # 多子图布局
        fig, axes = plt.subplots(2, 2, figsize=(15, 10))
        fig.suptitle('EDA高级分析结果', fontsize=16)
        
        signal = eda_data['signal']
        timestamps = eda_data.get('timestamps', np.arange(len(signal)))
        
        # 1. 原始信号 vs 预处理信号
        axes[0, 0].plot(timestamps, signal, 'b-', alpha=0.7, label='原始信号')
        if 'preprocessed_signal' in results:
            axes[0, 0].plot(timestamps, results['preprocessed_signal'], 'r-', label='预处理信号')
        axes[0, 0].set_title('信号预处理对比')
        axes[0, 0].set_xlabel('时间 (s)')
        axes[0, 0].set_ylabel('EDA (μS)')
        axes[0, 0].legend()
        axes[0, 0].grid(True, alpha=0.3)
        
        # 2. 峰值检测结果
        processed_signal = results.get('preprocessed_signal', signal)
        axes[0, 1].plot(timestamps, processed_signal, 'b-', alpha=0.7, label='EDA信号')
        
        if 'peaks' in results and results['peaks']:
            peak_times = [p.get('peak_time', 0) for p in results['peaks']]
            peak_amplitudes = [processed_signal[int(p.get('peak_index', 0))] for p in results['peaks'] 
                             if p.get('peak_index', 0) < len(processed_signal)]
            
            axes[0, 1].scatter(peak_times, peak_amplitudes, color='red', s=50, 
                             label=f'SCR峰值 ({len(peak_times)}个)', zorder=5)
        
        axes[0, 1].set_title('峰值检测结果')
        axes[0, 1].set_xlabel('时间 (s)')
        axes[0, 1].set_ylabel('EDA (μS)')
        axes[0, 1].legend()
        axes[0, 1].grid(True, alpha=0.3)
        
        # 3. 频谱分析
        from scipy import signal as scipy_signal
        freqs, psd = scipy_signal.welch(processed_signal, 
                                      eda_data.get('sampling_rate', 4.0), 
                                      nperseg=min(256, len(processed_signal)//4))
        
        axes[1, 0].semilogy(freqs, psd)
        axes[1, 0].set_title('功率谱密度')
        axes[1, 0].set_xlabel('频率 (Hz)')
        axes[1, 0].set_ylabel('功率谱密度')
        axes[1, 0].grid(True, alpha=0.3)
        
        # 4. 质量评估雷达图
        if 'quality_assessment' in results:
            quality = results['quality_assessment']
            
            # 质量维度
            dimensions = ['完整性', '噪声', '稳定性', '伪迹', '一致性', '生理性']
            scores = [
                quality.get('completeness_score', 0),
                quality.get('noise_score', 0),
                quality.get('stability_score', 0),
                quality.get('artifact_score', 0),
                quality.get('consistency_score', 0),
                quality.get('physiological_score', 0)
            ]
            
            # 创建雷达图
            angles = np.linspace(0, 2*np.pi, len(dimensions), endpoint=False).tolist()
            scores += scores[:1]  # 闭合图形
            angles += angles[:1]
            
            axes[1, 1].plot(angles, scores, 'o-', linewidth=2, label='质量评分')
            axes[1, 1].fill(angles, scores, alpha=0.25)
            axes[1, 1].set_xticks(angles[:-1])
            axes[1, 1].set_xticklabels(dimensions)
            axes[1, 1].set_ylim(0, 1)
            axes[1, 1].set_title('信号质量评估')
            axes[1, 1].grid(True)
        
        plt.tight_layout()
        plt.savefig(output_path / "advanced_analysis.png", dpi=300, bbox_inches='tight')
        plt.close()
        
    except Exception as e:
        logger.warning(f"创建高级可视化失败: {str(e)}")

def create_detailed_text_report(eda_data: Dict[str, Any], 
                              results: Dict[str, Any]) -> str:
    """创建详细的文本报告"""
    report_lines = []
    
    report_lines.append("EDA高级分析详细报告")
    report_lines.append("=" * 60)
    report_lines.append(f"生成时间: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M:%S')}")
    report_lines.append("")
    
    # 数据概况
    report_lines.append("1. 数据概况")
    report_lines.append("-" * 30)
    signal_length = len(eda_data['signal'])
    sampling_rate = eda_data.get('sampling_rate', 4.0)
    duration = signal_length / sampling_rate
    
    report_lines.append(f"信号长度: {signal_length} 个采样点")
    report_lines.append(f"采样率: {sampling_rate} Hz")
    report_lines.append(f"信号时长: {duration:.2f} 秒")
    report_lines.append(f"平均EDA: {np.mean(eda_data['signal']):.4f} μS")
    report_lines.append(f"EDA范围: [{np.min(eda_data['signal']):.4f}, {np.max(eda_data['signal']):.4f}] μS")
    report_lines.append("")
    
    # 预处理结果
    if 'preprocessing_info' in results:
        report_lines.append("2. 预处理结果")
        report_lines.append("-" * 30)
        
        preprocessing_info = results['preprocessing_info']
        report_lines.append(f"质量评分: {preprocessing_info.get('quality_score', 0):.3f}")
        
        steps = preprocessing_info.get('processing_steps', [])
        report_lines.append(f"处理步骤 ({len(steps)} 个):")
        for step in steps:
            report_lines.append(f"  - {step}")
        report_lines.append("")
    
    # 峰值检测结果
    if 'peaks' in results:
        report_lines.append("3. 峰值检测结果")
        report_lines.append("-" * 30)
        
        peaks = results['peaks']
        report_lines.append(f"检测到SCR峰值: {len(peaks)} 个")
        
        if peaks:
            amplitudes = [p.get('amplitude', 0) for p in peaks]
            durations = [p.get('duration', 0) for p in peaks]
            
            report_lines.append(f"幅度统计:")
            report_lines.append(f"  平均幅度: {np.mean(amplitudes):.4f} μS")
            report_lines.append(f"  幅度范围: [{np.min(amplitudes):.4f}, {np.max(amplitudes):.4f}] μS")
            
            report_lines.append(f"持续时间统计:")
            report_lines.append(f"  平均持续时间: {np.mean(durations):.2f} 秒")
            report_lines.append(f"  持续时间范围: [{np.min(durations):.2f}, {np.max(durations):.2f}] 秒")
        
        report_lines.append("")
    
    # 指标分析
    if 'metrics' in results:
        report_lines.append("4. 指标分析")
        report_lines.append("-" * 30)
        
        metrics = results['metrics']
        report_lines.append(f"计算指标数量: {len(metrics)}")
        
        # 按类别组织指标
        basic_metrics = {}
        scr_metrics = {}
        frequency_metrics = {}
        
        for key, value in metrics.items():
            if any(x in key.lower() for x in ['mean', 'std', 'min', 'max', 'range']):
                basic_metrics[key] = value
            elif any(x in key.lower() for x in ['scr', 'peak', 'amplitude']):
                scr_metrics[key] = value
            elif any(x in key.lower() for x in ['frequency', 'power', 'spectral']):
                frequency_metrics[key] = value
        
        if basic_metrics:
            report_lines.append("基本统计指标:")
            for key, value in basic_metrics.items():
                report_lines.append(f"  {key}: {value:.4f}")
        
        if scr_metrics:
            report_lines.append("SCR相关指标:")
            for key, value in scr_metrics.items():
                report_lines.append(f"  {key}: {value:.4f}")
        
        if frequency_metrics:
            report_lines.append("频域指标:")
            for key, value in frequency_metrics.items():
                report_lines.append(f"  {key}: {value:.4f}")
        
        report_lines.append("")
    
    # 质量评估
    if 'quality_assessment' in results:
        report_lines.append("5. 质量评估")
        report_lines.append("-" * 30)
        
        quality = results['quality_assessment']
        report_lines.append(f"总体质量评分: {quality.get('overall_score', 0):.3f}/1.0")
        
        # 各维度评分
        dimensions = {
            'completeness_score': '数据完整性',
            'noise_score': '噪声水平',
            'stability_score': '信号稳定性',
            'artifact_score': '伪迹检测',
            'consistency_score': '信号一致性',
            'physiological_score': '生理有效性'
        }
        
        report_lines.append("各维度评分:")
        for key, name in dimensions.items():
            if key in quality:
                score = quality[key]
                report_lines.append(f"  {name}: {score:.3f}")
        
        # 问题和建议
        issues = quality.get('issues', [])
        if issues:
            report_lines.append(f"发现问题 ({len(issues)} 个):")
            for issue in issues:
                report_lines.append(f"  - {issue}")
        
        recommendations = quality.get('recommendations', [])
        if recommendations:
            report_lines.append(f"处理建议 ({len(recommendations)} 条):")
            for rec in recommendations:
                report_lines.append(f"  - {rec}")
        
        report_lines.append("")
    
    # 总结
    report_lines.append("6. 分析总结")
    report_lines.append("-" * 30)
    
    overall_quality = results.get('quality_assessment', {}).get('overall_score', 0)
    peak_count = len(results.get('peaks', []))
    
    if overall_quality > 0.8:
        quality_desc = "优秀"
    elif overall_quality > 0.6:
        quality_desc = "良好"
    elif overall_quality > 0.4:
        quality_desc = "一般"
    else:
        quality_desc = "较差"
    
    report_lines.append(f"数据质量: {quality_desc} ({overall_quality:.3f})")
    report_lines.append(f"SCR活动: 检测到 {peak_count} 个峰值")
    
    if peak_count > 0:
        scr_rate = peak_count / (duration / 60)  # 每分钟SCR数
        report_lines.append(f"SCR频率: {scr_rate:.2f} 个/分钟")
    
    report_lines.append("")
    report_lines.append("分析完成。")
    
    return "\n".join(report_lines)

# 主函数示例
if __name__ == "__main__":
    print("EDA处理器高级功能示例")
    print("=" * 60)
    
    # 运行高级处理管道示例
    print("\n1. 高级处理管道示例")
    advanced_results = advanced_processing_pipeline_example(output_dir="./output/advanced_example")
    
    # 运行自定义预处理示例
    print("\n2. 自定义预处理示例")
    preprocessing_results = custom_preprocessing_example()
    
    # 运行质量评估示例
    print("\n3. 质量评估示例")
    quality_results = quality_assessment_example()
    
    # 运行算法比较示例
    print("\n4. 算法比较示例")
    comparison_results = algorithm_comparison_example()
    
    print("\n所有高级示例运行完成！")